package com.wulis.provider.authority.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wulis.common.model.enums.DeletedStateEnum;
import com.wulis.common.support.BaseServiceImpl;
import com.wulis.provider.authority.mapper.RoleMenuMapper;
import com.wulis.provider.authority.model.entity.RoleMenu;
import com.wulis.provider.authority.service.RoleMenuService;

import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;

/**
 * 权限管理:角色-菜单表 Service实现类
 *
 * @author WuliBao
 * @date 2020-04-17
 */
@Slf4j
@Service
@AllArgsConstructor
public class RoleMenuServiceImpl extends BaseServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {
    private final RoleMenuMapper roleMenuMapper;
    
    /**
     * WEB:批量新增角色菜单关联关系
     * 
     * @param menuIds menuIds
     * @return int
     */
    @Override
    public int insertBatchRoleMenu(@NonNull Long roleId, @NonNull List<Long> menuIds) {
        // 批量新增角色菜单关联关系
        List<RoleMenu> roleMenus = menuIds.stream()
            .map(menuId -> new RoleMenu().setRoleId(roleId).setMenuId(menuId))
            .collect(Collectors.toList());
        if (!roleMenus.isEmpty()) {
            return roleMenuMapper.insertBatchDuplicateKeyUpdate(roleMenus);
        }
        return 0;
    }
    
    /**
     * WEB:修改角色菜单关联关系
     *
     * @param roleId roleId
     * @param menuIds menuIds
     * @return int
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBatchRoleMenu(@NonNull Long roleId, @NonNull List<Long> menuIds) {
        // 删除角色关联的菜单
        deleteRoleMenu(roleId);
        // 新增角色菜单关联关系
        return insertBatchRoleMenu(roleId, menuIds);
    }
    
    /**
     * WEB:删除角色菜单关联关系
     * 
     * @param roleId roleId
     * @return int
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteRoleMenu(@NonNull Long roleId) {
        // 删除角色菜单关联关系
        UpdateWrapper<RoleMenu> wrapper = new UpdateWrapper<>();
        wrapper.lambda().eq(RoleMenu::getRoleId, roleId);
        RoleMenu roleMenu = new RoleMenu();
        roleMenu.setDeleted(DeletedStateEnum.IS_DELETED.value());
        return roleMenuMapper.update(roleMenu, wrapper);
    }
}
